#include "exti.h"

void EXTI_config(void)
{
    EXTI_InitTypeDef EXTI_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOG, EXTI_PinSource2);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOG, EXTI_PinSource3);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOG, EXTI_PinSource4);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOG, EXTI_PinSource5);

    EXTI_InitStruct.EXTI_Line = EXTI_Line2 | EXTI_Line3 | EXTI_Line4 | EXTI_Line5;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI2_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI3_IRQn;
    NVIC_Init(&NVIC_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI4_IRQn;
    NVIC_Init(&NVIC_InitStruct);

    NVIC_InitStruct.NVIC_IRQChannel = EXTI9_5_IRQn;
    NVIC_Init(&NVIC_InitStruct);
}

void EXTI2_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line2) != RESET)
    {
        delay_ms(15);
        if (GPIO_ReadInputDataBit(KEY_GROUP, KEY1_PIN) == 0)
        {
            //流水灯加速
            led_speed_mode = (led_speed_mode + 1) % 5;
            while (GPIO_ReadInputDataBit(KEY_GROUP, KEY1_PIN) == 0)
                ;
            delay_ms(15);
        }

        EXTI_ClearITPendingBit(EXTI_Line2);
    }
}

void EXTI3_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line3) != RESET)
    {
        delay_ms(15);
        if (GPIO_ReadInputDataBit(KEY_GROUP, KEY2_PIN) == 0)
        {
            //流水灯自动手动模式切换
            led_water_mode = !led_water_mode;
            while (GPIO_ReadInputDataBit(KEY_GROUP, KEY2_PIN) == 0)
                ;
            delay_ms(15);
        }
        EXTI_ClearITPendingBit(EXTI_Line3);
    }
}

void EXTI4_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line4) != RESET)
    {
        delay_ms(15);
        if (GPIO_ReadInputDataBit(KEY_GROUP, KEY3_PIN) == 0)
        {
            //手动模式下，增加点亮灯的个数
            led_manual_light_num = (led_manual_light_num + 1) % 5;
            while (GPIO_ReadInputDataBit(KEY_GROUP, KEY3_PIN) == 0)
                ;
            delay_ms(15);
        }
        EXTI_ClearITPendingBit(EXTI_Line4);
    }
}

void EXTI9_5_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line5) != RESET)
    {
        // delay_ms(15);
        // if (GPIO_ReadInputDataBit(KEY_GROUP, KEY4_PIN) == 0)
        // {
        //     led_speed_mode = (led_speed_mode + 1) % 5;
        //     while (GPIO_ReadInputDataBit(KEY_GROUP, KEY4_PIN) == 0)
        //         ;
        //     delay_ms(15);
        // }
        EXTI_ClearITPendingBit(EXTI_Line5);
    }
}
